/*
* © 2010 Autodata Solutions Company. All Rights Reserved
* This source code is the confidential and proprietary information of Autodata Solutions Company.
* The user shall not, in whole or in part, copy, publish, disclose or make any use of this source code
* without the prior written consent of Autodata Solutions Company.
*/
Ext.ns('net.autodata.compare.editorial');
(function() {

    var DQ = Ext.DomQuery;

    var Store = Ext.extend(net.autodata.data.Store, {

        constructor: function(cfg) {
            cfg = cfg || {};

            Ext.apply(cfg, {
                autoLoad: false,
                reader: new Ext.data.JsonReader({
                    root: 'rows',
                    fields: [
                        { name: 'acode' },
                        { name: 'ymm' },
						{ name: 'title' },
						{ name: 'exerpt' },
						{ name: 'url' }
					]
                })
            });

            Store.superclass.constructor.call(this, cfg);
        }
    });

    /**
    * Display a vehicle with a customizable view
    * @class EditorialPanel
    * @extends Ext.BoxComponent
    * @namespace net.autodata.compare.editorial
    */
    var Panel = Ext.extend(Ext.BoxComponent, {

        autoEl: {
            tag: 'div',
            cls: 'editorial-panel'
        },

        /**
        * The editorial content's title bar text.
        * @property title
        * @type String
        */
        title: 'To view the editorial content of a vehicle, click on the "Select Vehicle" button below the vehicle image',

        /**
        * The read more hyperlink text
        * @property readmore
        * @type String
        */
        readmore: 'Read more',

        /**
        * @property emptyText
        * @type String
        */
        emptyText: undefined,

        /**
        * @property tbar
        * @type Object
        */
        tbar: undefined,

        /**
        * @property view
        * @type Object
        */
        view: undefined,

        /**
        * @property store
        * @type Object
        */
        store: undefined,

        baseVehicle: undefined,
        competitors: undefined,

        /**
        * @property emptyBody
        * @type Ext.BoxComponent
        * @private
        */
        emptyBody: undefined,

        constructor: function(cfg) {
            this.addEvents({ 'datachanged': true });

            cfg = cfg || {};

            var storeCfg = cfg.storeCfg || {};
            delete cfg.storeCfg;
            Ext.apply(storeCfg, {
                listeners: {
                    'loadexception': this.onLoadException,
                    'load': this.onLoad,
                    scope: this
                }
            });
            this.store = new Store(storeCfg);

            Panel.superclass.constructor.call(this, cfg);
        },

        initComponent: function() {
            Panel.superclass.initComponent.apply(this, arguments);
            var tb = this.getToolbar();
            tb.init(this);

            var view = this.getView();
            view.init(this);
            this.relayEvents(view, ['change', 'remove']);

            this.emptyBody = new Ext.BoxComponent({
                autoEl: {
                    tag: 'div',
                    cls: 'editorialpanel-emptybody'
                },
                html: '<div class="empty-text">' + this.emptyText + '</div>',
                hideMode: 'display',
                hidden: true
            });
        },

        // Public Methods

        /**
        * @method getView
        * @returns net.autodata.compare.editorial.EditorialView
        */
        getView: function() {
            if (!this.view) {
                this.view = new net.autodata.compare.editorial.EditorialView(this.viewCfg);
            }

            return this.view;
        },

        /**
        * Supply the vehicles this panel is supposed to display and trigger the load
        * @method setVehicles
        * @param {Vehicle[]} vehicles Array of Vehicle objects (Base/Competitor)
        */
        setVehicles: function(baseVehicle, competitors) {
            if (!baseVehicle) {
                throw 'The baseVehicle parameter cannot be null';
            }

            this.baseVehicle = baseVehicle;
            this.competitors = competitors;

            //load the store
            var acodes = [baseVehicle.acode];
            Ext.each(this.competitors, function(v) {
                if (v) {
                    acodes.push(v.acode ? v.acode : '');
                }
            }, this);

            if (acodes.length > 0) {
                this.getStore().load({ params: { acodes: acodes} });
            }
        },

        /**
        * Finding the matching vehicle information for the given acode
        * @param {String} acode
        * @return {Vehicle} Undefined if no match is found
        */
        getVehicle: function(acode) {
            if (this.baseVehicle.acode === acode) {
                return this.baseVehicle;
            }

            for (var i = 0; i < this.competitors.length; i++) {
                var competitor = this.competitors[i];
                if (competitor && competitor.acode === acode) {
                    return competitor;
                }
            }

            return undefined;
        },

        /**
        * @method getToolbar
        * @returns Object
        */
        getToolbar: function() {
            if (!this.tbar) {
                this.tbar = new new net.autodata.compare.CompetitorToolbar({
                    tbar: new net.autodata.compare.EditorialToolbarView()
                });
            }

            return this.tbar;
        },

        /**
        * @method getData
        * @returns Object
        */
        getData: function() {
            return this.data;
        },

        // Private methods

        /**
        * @method getStore
        * @returns net.autodata.data.Store
        * @private
        */
        getStore: function() {
            if (!this.store) {
                this.store = new Store();
            }
            return this.store;
        },

        // Public Event Handlers

        /**
        * Panel on vehicle selected event handler.
        * @method onVehicleSelected
        * @param {String} acode The selected competitors acode.
        */
        onVehicleSelected: function(acode) {
            if (acode) {
                var vehicle = this.getVehicle(acode);

                if (vehicle) {
                    ASC.apply(vehicle, {
                        text: this.title
                    });
                }

                var data = {
                    vehicle: vehicle,
                    details: []
                };

                var store = this.getStore();
                store.filter('acode', acode);

                var readmore = this.readmore;

                if (store != null && store.getCount() > 0) {
                    store.each(function(record) {
                        this.details.push({
                            title: record.get('title'),
                            summary: record.get('summary'),
                            url: record.get('url'),
                            readmore: readmore
                        });
                    }, data);
                }

                store.clearFilter();

                this.data = data;

                var view = this.getView();
                view.refresh();
            }
        },

        // Private Event Handlers

        /**
        * @method onRender
        * @private
        */
        onRender: function() {
            Panel.superclass.onRender.apply(this, arguments);

            var view = this.getView();
            view.render();

            this.emptyBody.render(this.el);
        },

        onLoadException: function() {
            var store = this.getStore();
            if (store) {
                store.removeAll();
            }

            var view = this.getView();
            if (view) {
                view.onDestroy();
            }

            this.emptyBody.show();
        },

        /**
        * Panel's store load event handler.
        * @method onLoad
        * @private
        */
        onLoad: function(store, records) {
            if (this.emptyBody) {
                this.emptyBody.hide();
            }

            var tb = this.getToolbar();
            var view = tb.getView();
            var selectedAcode;
            if (view != null && view.buttonIdPrefix != null) {
                for (var x = 0; x < records.length; ++x) {
                    var r = records[x];
                    if (r) {
                        var acode = r.get('acode');
                        if (acode != null && acode != '') {
                            if (!selectedAcode) {
                                selectedAcode = acode;
                            }
                        }
                    }
                }
            }

            if (selectedAcode) {
                var el = tb.getComponent(view.buttonIdPrefix + selectedAcode);
                if (el != null) {
                    el.toggle(true, false);
                }

                this.onVehicleSelected(selectedAcode);
            }
        }
    });

    net.autodata.compare.editorial.EditorialPanel = Panel;
})();
